package com.feihong.txgw.ui.activity.kaika;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.kaika.KaikaNewPackageEntity;
import com.feihong.txgw.model.PRODUCT_TYPE;
import com.feihong.txgw.model.bean.kaika.KaikaYuYueOrderInfo;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.kaika.KaikaIntentType;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.just.agentweb.AgentWeb;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.kaika
 * @class describe:  开卡新套餐选择界面
 * @time 2017/9/22 13:32
 * @change
 * @chang time
 * @class describe
 */
public class KaikaNewPackageActivity extends BaseActivity implements View.OnClickListener {

    private AgentWeb mAgentWeb;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    @BindView(R.id.kaika_new_package_framelayout) RelativeLayout mFramLayout;
    @BindView(R.id.btn_back) ImageView mBackBtn;
    private String isFrom;

    private KaikaYuYueOrderInfo mKaikaYuYueOrderInfo;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 10) {
                loadPage();
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_new_paceage_layout;
    }

    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                Message message = Message.obtain();
                message.what = 10;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        KaikaManager.getmKaikaManager().addStack(this);
        mKaikaYuYueOrderInfo = KaikaYuYueOrderInfo.getInstance();
        setPageTitle("选择套餐");
        mBackBtn.setOnClickListener(this);
        String packageKeySign = getIntent().getStringExtra(KaikaIntentType.PACKAGE_INTENT_TYPE_KEY);
        if (!TextUtils.isEmpty(packageKeySign) && packageKeySign.equals(KaikaIntentType.INTENT_FROM_YUYUE_PAGE)) {
            isFrom = KaikaIntentType.INTENT_FROM_YUYUE_PAGE;
        } else if (!TextUtils.isEmpty(packageKeySign) && packageKeySign.equals(KaikaIntentType.INTENT_FROM_ADDRESS_PAGE)) {
            isFrom = KaikaIntentType.INTENT_FROM_ADDRESS_PAGE;
        } else if (!TextUtils.isEmpty(packageKeySign) && packageKeySign.equals(KaikaIntentType.INTENT_FROM_HOME_PAGE)) {
            isFrom = KaikaIntentType.INTENT_FROM_HOME_PAGE;
        }
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mFramLayout, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()//
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()//
                .ready();
        refreshToken();
    }

    @Override
    public void bindData() {
    }

    private void loadPage() {
        String url = HttpTools.KAIKA_STEP3_NEW_WEBURL + "?";
        HashMap<String, String> mParams = new HashMap<>();
        mParams.put("citycode", UserLoginInfo.getUserCityInfo().getCityCode());
        String params = new SignToken().setSigen(mParams);
        url = url + params;
        LogUtils.i(TAG+": 无卡开户，选择套餐url:" + url);
        mAgentWeb = mPreAgentWeb.go(url);
        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new KaikaNewPackageInterface(mAgentWeb, this, newPackageCallBack));
        //水平不显示
        mAgentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);
        //垂直不显示
        mAgentWeb.getWebCreator().getWebView().setVerticalScrollBarEnabled(false);
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            showSystemToast(url);
            return true;
            // return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {


            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

    };

    NewPackageCallBack newPackageCallBack = new NewPackageCallBack() {
        @Override
        public void getPacakgeInfo(String packageInfo) {
            try {
                JSONObject jsonObject = new JSONObject(packageInfo);
                KaikaNewPackageEntity kaikaNewPackageEntity = JSON.parseObject(jsonObject.optString("params"), KaikaNewPackageEntity.class);
                kaikaNewPackageEntity.setType(PRODUCT_TYPE.TAG_PHONE_TARIFF);
                mKaikaYuYueOrderInfo.setmPackageId(kaikaNewPackageEntity.getSpec_id());
                mKaikaYuYueOrderInfo.setmPackageInfo(kaikaNewPackageEntity.getSpec_name());
                mKaikaYuYueOrderInfo.setmAddressId(null);
                mKaikaYuYueOrderInfo.setmAddress(null);
                Intent intent = new Intent(KaikaNewPackageActivity.this, KaiKaStep2Activity.class);
                intent.putExtra(KaikaIntentType.PHONE_NUMBER_INTENT_TYPE_KEY, KaikaIntentType.INTENT_FROM_PACKAGE_PAGE);
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                if (isFrom.equals(KaikaIntentType.INTENT_FROM_HOME_PAGE)) {
                    Intent intent = new Intent(this, KaikaNoCardOperateActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    finish();
                }
                break;
            default:
                break;
        }
    }

    public interface NewPackageCallBack {
        void getPacakgeInfo(String packageInfo);
    }

    @Override
    public void onBackPressedSupport() {
        if (isFrom.equals(KaikaIntentType.INTENT_FROM_HOME_PAGE)) {
            Intent intent = new Intent(this, KaikaNoCardOperateActivity.class);
            startActivity(intent);
            finish();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
    }
}
